package com.swak.reactivex.p2p.exchange;

import java.util.List;
import java.util.Map;
import java.util.Set;

import com.swak.reactivex.p2p.PeerID;
import com.swak.reactivex.transport.ExchangeChannel;
import com.swak.utils.Lists;
import com.swak.utils.Maps;

@Deprecated
public class ExchangeChannels {

	private Map<PeerID, List<ExchangeChannel>> channels = Maps.newConcurrentMap();

	public boolean containsKey(PeerID peerID) {
		return channels.containsKey(peerID);
	}

	public ExchangeChannel get(PeerID peerID) {
		List<ExchangeChannel> channels = this.channels.get(peerID);
		return channels != null && !channels.isEmpty() ? channels.get(0) : null;
	}

	public ExchangeChannels put(PeerID peerID, ExchangeChannel channel) {
		List<ExchangeChannel> channels = this.channels.computeIfAbsent(peerID, (key) -> Lists.newArrayList());
		channels.add(channel);
		return this;
	}

	public List<ExchangeChannel> remove(PeerID peerID) {
		List<ExchangeChannel> channels = this.channels.remove(peerID);
		if (channels != null) {
			for (ExchangeChannel channel : channels) {
				try {
					if (channel.isConnected()) {
						channel.close();
					}
				} catch (Exception e) {
				}
			}
		}
		return channels;
	}

	public Set<PeerID> peers() {
		return channels.keySet();
	}
}
